import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const settingsDir = path.resolve(__dirname, './src/yaml/settings'); // YAML 文件夹路径
const outputFilePath = path.resolve(__dirname, 'settings.yaml'); // 输出文件路径

//从theme.yaml获取settingName
const themeYamlFile = fs.readFileSync('theme.yaml', 'utf8');
const themeYaml = yaml.load(themeYamlFile)

function mergeSettings() {
    const files = fs.readdirSync(settingsDir);
    const mergedSettings = { apiVersion: 'v1alpha1', kind: 'Setting', metadata: { name: themeYaml.spec.settingName }, spec: { forms: [] } };

    files.forEach(file => {
        if (file.endsWith('.yaml')) {
            const filePath = path.join(settingsDir, file);
            const fileContent = fs.readFileSync(filePath, 'utf8');
            const yamlContent = yaml.load(fileContent);

            mergedSettings.spec.forms.push(yamlContent); // 将每个 group 添加到 forms 中
        }
    });
    const newSettingsYaml = yaml.dump(mergedSettings, { lineWidth: -1 });

    // 检查当前的 settings.yaml 内容
    if (fs.existsSync(outputFilePath)) {
        const currentSettingsYaml = fs.readFileSync(outputFilePath, 'utf8');
        if (currentSettingsYaml === newSettingsYaml) {
            console.log('Settings file is up to date. No changes made.');
            return; // 如果内容相同，则不更新
        }
    }

    // 写入合并后的 settings.yaml 文件
    fs.writeFileSync(outputFilePath, newSettingsYaml);
    console.log(`Merged settings written to ${outputFilePath}`);
}

mergeSettings();